package cn.com.headfree.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.aostarit.smcrypto.CipherMode;
import com.aostarit.smcrypto.Sm2Utils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.logging.LogLevel;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gta.edu.sdk.base.controller.BaseController;
import com.gta.edu.sdk.common.dto.LogInfo;
import com.gta.edu.sdk.common.dto.LogType;
import com.gta.edu.sdk.common.dto.LoginUserInfo;
import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.config.DateJsonValueProcessor;
import com.gta.edu.sdk.util.EhCacheUtil;
import com.gta.edu.sdk.util.RedisClusterUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.service.IscSsoCall;
import cn.com.headfree.dto.MenuDto;
import cn.com.headfree.entity.TCommonPublicMenu;
import cn.com.headfree.service.IUserInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@RestController
@RequestMapping(value = "/menu", produces = "application/json;charset=UTF-8")
public class MenuController extends BaseController {
	private static final Logger log = Logger.getLogger(MenuController.class);

	@Value("${isc.sso.url}")
	private String isoUrl;

	@Value("${redis.menu.timelong}")
	private int redisMenuTimelong;

	@Value("${redis.domainId.timelong}")
	private int redisDomainIdTimelong;

	@Value("${redis.appId.timelong}")
	private int redisAppIdTimelong;

	@Autowired
	private IUserInfoService userInfoService;

	private static String publicKey = "040462616C1B5DB30C75EB696E8609B3899C8C1165B958360F4F8C53D26E2EEA4ED3E6E1BD85804A030A27B6DC72ED4FB2C00AB518187D60471234BF257E9BF5C2";

	/***
	 * @description 获取当前登录用户信息
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:26:32
	 * @return ResultData
	 */
	@RequestMapping(value = "/loginUserInfo", method = RequestMethod.GET)
	public ResultData loginUserInfo(HttpServletRequest request) {
		ResultData result = new ResultData();
		try {
			LoginUserInfo loginUserInfo = this.getLongUserInfo();
			if (loginUserInfo == null) {
				result.setSuccess(false);
				result.setErrorMsg("调用接口失败，可能网络不通，请稍后重试！");
			} else {
				result.setData(JSONObject.fromObject(loginUserInfo).toString());
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("程序调用出现了异常，请重试！");
		}
		return result;
	}

	/**
	 * @description 根据登录用户的登录名获取用户所属的角色集合
	 * @author fengya
	 * @date 2020年7月4日 上午10:28:41
	 * @param loginName 对应登录用户的iscUserSourceId字段值
	 * @param token
	 * @return ResultData
	 */
	@RequestMapping(value = "/findLabelByLoginName/{loginName}/{domainId}", method = RequestMethod.GET)
	public ResultData findLabelByLoginName(@PathVariable("loginName") String loginName, @PathVariable("domainId") String domainId) {
		ResultData result = new ResultData();
		try {
			String cacheKey = "userLabel_" + domainId + "_" + loginName;
			String resultString = EhCacheUtil.getValue(cacheKey);
			if (!StringUtil.isNullOrEmpty(resultString)) {
				result.setData(resultString);
				return result;
			}
			resultString = RedisClusterUtil.getInstance().getString(cacheKey);
			if (!StringUtil.isNullOrEmpty(resultString)) {
				result.setData(resultString);
				EhCacheUtil.put(cacheKey, resultString);
				return result;
			}
			JSONArray userLabelArray = new JSONArray();
			ResultData labelsResult = this.findLabelByDomainId(domainId, 1000, 0);
			if (labelsResult.isSuccess()) {
				JSONObject labelResult = JSONObject.fromObject(labelsResult.getData());
				JSONArray array = labelResult.getJSONArray("data");
				if (array != null && array.size() > 0) {
					JSONObject labelObj = null;
					ResultData usersData = null;
					JSONArray userArray = null;
					JSONObject userObj = null;
					for (int i = 0; i < array.size(); i++) {
						labelObj = array.getJSONObject(i);
						usersData = this.findUserByLabelId(labelObj.getString("id"), domainId);
						if (usersData.getData() != null) {
							userArray = JSONArray.fromObject(usersData.getData());
							for (int j = 0; j < userArray.size(); j++) {
								userObj = userArray.getJSONObject(j);
								if (loginName.equalsIgnoreCase(userObj.getString("loginName"))) {
									userLabelArray.add(userLabelArray.size(), labelObj);
									break;
								}
							}
						}
					}
				}
			}
			result.setData(userLabelArray);
			EhCacheUtil.put(cacheKey, userLabelArray.toString());
			RedisClusterUtil.getInstance().setString(cacheKey, userLabelArray.toString(), redisDomainIdTimelong);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("程序调用出现了异常，请重试！");
		}
		return result;
	}

	/***
	 * @description 根据角色ID获得角色下所有的人员信息
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @return ResultData
	 */
	@RequestMapping(value = "/findUserByLabelId/{labelId}/{domainId}", method = RequestMethod.GET)
	public ResultData findUserByLabelId(@PathVariable("labelId") String labelId, @PathVariable("domainId") String domainId) {
		ResultData result = new ResultData();
		String redisUserByLabelKey = domainId + "_labelId_" + labelId;
		String usersStr = EhCacheUtil.getValue(redisUserByLabelKey);
		if (!StringUtil.isNullOrEmpty(usersStr)) {
			result.setData(usersStr);
			return result;
		}
		usersStr = RedisClusterUtil.getInstance().getString(redisUserByLabelKey);
		if (!StringUtil.isNullOrEmpty(usersStr)) {
			result.setData(usersStr);
			EhCacheUtil.put(redisUserByLabelKey, usersStr);
			return result;
		}
		String url = "/getUserByLabelId/" + labelId;
		String userData = null;
		try {
			userData = IscSsoCall.iscPostApi(url);
			log.info("根据角色【" + labelId + "】获取人员：" + userData);
			if (!StringUtil.isNullOrEmpty(userData)) {
				JSONObject data = JSONObject.fromObject(userData);
				if (data.getInt("resultCode") == 200) {
					JSONArray array = data.getJSONArray("data");
					result.setData(array.toString());
					EhCacheUtil.put(redisUserByLabelKey, array.toString());
					RedisClusterUtil.getInstance().setString(redisUserByLabelKey, array.toString(), redisDomainIdTimelong);
				} else {
					throw new Exception(data.getString("resultInfo"));
				}
			} else {
				throw new Exception("请求接口获得空数据！");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg(e.getMessage());
			log.error("通过角色ID[" + labelId + "]获取角色下的用户接口调用出现了错误！", e);
		}
		return result;
	}

	/***
	 * @description 根据用户ID获得人员信息
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @return ResultData
	 */
	@RequestMapping(value = "/findUserByUserId/{userId}", method = RequestMethod.GET)
	public ResultData findUserByUserId(@PathVariable("userId") String userId) {
		ResultData result = new ResultData();
		String resultUserKey = "user_" + userId;
		String userInfo = EhCacheUtil.getValue(resultUserKey);
		if (!StringUtil.isNullOrEmpty(userInfo)) {
			result.setData(userInfo);
			return result;
		}
		userInfo = RedisClusterUtil.getInstance().getString(resultUserKey);
		if (!StringUtil.isNullOrEmpty(userInfo)) {
			result.setData(userInfo);
			EhCacheUtil.put(resultUserKey, userInfo);
			return result;
		}
		try {
			userId = new Sm2Utils(CipherMode.C1C3C2).encryptFromText(publicKey, userId);
		}catch(Exception e){
			log.info("getUserById 加密报错{} ",e);
		}
		String url = "/getUserById/" + userId;
		try {
			String userResult = IscSsoCall.iscPostApi(url);
			if (!StringUtil.isNullOrEmpty(userResult)) {
				JSONObject userResultData = JSONObject.fromObject(userResult);
				if (userResultData.getInt("resultCode") == 200) {
					JSONArray userJSONArray = userResultData.getJSONArray("data");
					if (userJSONArray != null && userJSONArray.size() > 0) {
						EhCacheUtil.put(resultUserKey, userJSONArray.getJSONObject(0).toString());
						RedisClusterUtil.getInstance().setString(resultUserKey, userJSONArray.getJSONObject(0).toString(), redisDomainIdTimelong);
						result.setData(userJSONArray.getJSONObject(0).toString());
					}
				} else {
					throw new Exception(userResultData.getString("resultInfo"));
				}
			} else {
				throw new Exception("请求接口获得空数据！");
			}
		} catch (Exception e) {
			log.error("通过用户ID[" + userId + "]获取用户信息的接口调用出现了错误！", e);
		}
		return result;
	}

	/***
	 * @description 根据用户ID和应用ID获取业务域
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @return ResultData
	 */
	@RequestMapping(value = "/findLabelByDomainId/{domainId}/{pageSize}/{pageNo}", method = RequestMethod.GET)
	public ResultData findLabelByDomainId(@PathVariable("domainId") String domainId, @PathVariable("pageSize") int pageSize, @PathVariable("pageNo") int pageNo) {
		ResultData result = new ResultData();
		String labelData = null;
		String redisLabelKey = "label_" + domainId + "_" + pageSize + "_" + pageNo;
		labelData = EhCacheUtil.getValue(redisLabelKey);
		if (!StringUtil.isNullOrEmpty(labelData)) {
			result.setData(labelData);
			return result;
		}
		labelData = RedisClusterUtil.getInstance().getString(redisLabelKey);
		if (!StringUtil.isNullOrEmpty(labelData)) {
			result.setData(labelData);
			EhCacheUtil.put(redisLabelKey, labelData);
			return result;
		}
		String url = "/label/list/" + domainId + "/" + pageSize + "/" + pageNo;
		try {
			labelData = IscSsoCall.iscPostApi(url);
			log.info("根据业务域获取的角色信息:" + labelData);
			if (!StringUtil.isNullOrEmpty(labelData)) {
				JSONObject data = JSONObject.fromObject(labelData);
				if (data.getInt("resultCode") == 200) {
					EhCacheUtil.put(redisLabelKey, labelData);
					RedisClusterUtil.getInstance().setString(redisLabelKey, labelData, redisDomainIdTimelong);
					result.setData(labelData);
				} else {
					throw new Exception(data.getString("resultInfo"));
				}
			} else {
				throw new Exception("请求接口获得空数据！");
			}
		} catch (Exception e) {
			log.error("通过业务域ID[" + domainId + "]获取对应的角色信息的接口调用出现了错误！", e);
		}
		return result;
	}

	/***
	 * @description 根据用户ID和应用ID获取业务域
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @return ResultData
	 */
	@RequestMapping(value = "/findLabelByDomainId/{pageSize}/{pageNo}", method = RequestMethod.GET)
	public ResultData findLabelByDomainId(@PathVariable("pageSize") @RequestParam(required = true) int pageSize, @PathVariable("pageNo") @RequestParam(required = true) int pageNo) {
		ResultData result = new ResultData();
		String appIdDomainKey = "domainId";
		String domainId = RedisClusterUtil.getInstance().getString(appIdDomainKey);
		if (StringUtil.isNullOrEmpty(domainId)) {
			result.setSuccess(false);
			result.setErrorMsg("获取业务ID为空！");
			log.error("获取业务ID为空！");
			return result;
		} else {
			String labelData = null;
			String redisLabelKey = "label_" + domainId + "_" + pageSize + "_" + pageNo;
			labelData = EhCacheUtil.getValue(redisLabelKey);
			if (!StringUtil.isNullOrEmpty(labelData)) {
				result.setData(labelData);
				return result;
			}
			labelData = RedisClusterUtil.getInstance().getString(redisLabelKey);
			if (!StringUtil.isNullOrEmpty(labelData)) {
				result.setData(labelData);
				EhCacheUtil.put(redisLabelKey, labelData);
				return result;
			}
			String url = "/label/list/" + domainId + "/" + pageSize + "/" + pageNo;
			try {
				labelData = IscSsoCall.iscPostApi(url);
				if (!StringUtil.isNullOrEmpty(labelData)) {
					JSONObject data = JSONObject.fromObject(labelData);
					if (data.getInt("resultCode") == 200) {
						EhCacheUtil.put(redisLabelKey, labelData);
						RedisClusterUtil.getInstance().setString(redisLabelKey, labelData, redisDomainIdTimelong);
						result.setData(labelData);
					} else {
						throw new Exception(data.getString("resultInfo"));
					}
				} else {
					throw new Exception("请求接口获得空数据！");
				}
			} catch (Exception e) {
				log.error("通过业务域ID[" + domainId + "]获取对应的角色信息的接口调用出现了错误！", e);
			}
		}
		return result;
	}

	/***
	 * @description 根据用户ID和资源ID获取用户拥有的菜单数据
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @param userId
	 * @param resId
	 * @return ResultData
	 */
	@RequestMapping(value = "/findUserResourceByInterface/{resId}/{userId}/{code}", method = RequestMethod.GET)
	public ResultData findUserResourceByInterface(@PathVariable("resId") String resId, @PathVariable("userId") String userId, @PathVariable("code") String code) {
		ResultData result = new ResultData();
		String key = userId + "-" + resId + "-" + code;
		JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		String redisMenuData = EhCacheUtil.getValue(key);
//		String redisMenuData = null;
		if (!StringUtil.isNullOrEmpty(redisMenuData)) {
			this.madeMenu(redisMenuData, resId, null, result, cfg);
			return result;
		} else {
			redisMenuData = RedisClusterUtil.getInstance().getString(key);
//			redisMenuData = null;
			if (!StringUtil.isNullOrEmpty(redisMenuData)) {
				EhCacheUtil.put(key, redisMenuData);
				this.madeMenu(redisMenuData, resId, null, result, cfg);
				return result;
			}
		}
		String url = "/userResource/allChildResource/" + userId + "/" + resId;
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		try {
			String menuData = IscSsoCall.appInfoApi(url);
			if (!StringUtils.isEmpty(menuData)) {
				JSONObject jsonMenuData = JSONObject.fromObject(menuData);
				if (jsonMenuData.get("resultCode") != null) {
					int resultCode = jsonMenuData.getInt("resultCode");
					if (resultCode == 200) {
						EhCacheUtil.put(key, jsonMenuData.getString("data"));
						RedisClusterUtil.getInstance().setString(key, jsonMenuData.getString("data"), redisMenuTimelong);
						this.madeMenu(jsonMenuData.getString("data"), resId, null, result, cfg);
						return result;
					}
				}
			}
		} catch (Exception e) {
			log.error(JSONObject.fromObject(null, cfg).toString(), e);
		}
		return result;
	}

	/***
	 * @description 根据用户ID和资源ID获取用户拥有的菜单数据
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @param userId
	 * @param resId
	 * @return ResultData
	 */
	@RequestMapping(value = "/findUserResourceByResId/{resId}", method = RequestMethod.GET)
	public ResultData findUserResourceByResId(@PathVariable("resId") String resId, HttpServletRequest request) {
		ResultData result = this.loginUserInfo(request);
		if (!result.isSuccess()) {
			return result;
		} else {
			Object data = result.getData();
			if (data != null) {
				JSONObject jsonData = JSONObject.fromObject(data);
				String userId = jsonData.getString("iscUserId");
				if (!StringUtils.isEmpty(userId)) {
					String token = this.getValueFromCookie("token", request);
					String key = userId + "-" + resId + "_" + token;
					JsonConfig cfg = new JsonConfig();
					cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
					String redisMenuData = EhCacheUtil.getValue(key);
//					String redisMenuData = null;
					if (!StringUtil.isNullOrEmpty(redisMenuData)) {
						this.madeMenu(redisMenuData, resId, null, result, cfg);
						return result;
					} else {
						redisMenuData = RedisClusterUtil.getInstance().getString(key);
//						redisMenuData = null;
						if (!StringUtil.isNullOrEmpty(redisMenuData)) {
							EhCacheUtil.put(key, redisMenuData);
							this.madeMenu(redisMenuData, resId, null, result, cfg);
							return result;
						}
					}
					String url = "/userResource/allChildResource/" + userId + "/" + resId;
					LogInfo logInfo = new LogInfo();
					String logId = UUID.randomUUID().toString();
					logInfo.setId(logId);
					logInfo.setSip(request.getRemoteAddr());
					logInfo.setDip(this.isoUrl);
					logInfo.setDip_service(url);
					logInfo.setLogType(LogType.receive.toString());
					logInfo.setTime(new Date());
					cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
					try {
						String menuData = IscSsoCall.appInfoApi(url);
						logInfo.setLevel(LogLevel.INFO.toString());
						logInfo.setLogMessage(menuData);
						log.info(JSONObject.fromObject(logInfo, cfg).toString());
						if (!StringUtils.isEmpty(menuData)) {
							JSONObject jsonMenuData = JSONObject.fromObject(menuData);
							if (jsonMenuData.get("resultCode") != null) {
								int resultCode = jsonMenuData.getInt("resultCode");
								if (resultCode == 200) {
									EhCacheUtil.put(key, jsonMenuData.getString("data"));
									RedisClusterUtil.getInstance().setString(key, jsonMenuData.getString("data"), redisMenuTimelong);
									// 解析出业务域ID，根据用户ID和业务域ID写入到redis中

									JSONArray menuArr = jsonMenuData.getJSONArray("data");
									String appIdDomainKey = "domainId";
									String sysAppIdKey = token + "_appId";
									if (menuArr != null && menuArr.size() > 0) {
										JSONObject menuObj = menuArr.getJSONObject(0);
										String domainId = menuObj.getString("domainId");
										String appId = menuObj.getString("appId");
										RedisClusterUtil.getInstance().setString(appIdDomainKey, domainId, this.redisDomainIdTimelong);
										RedisClusterUtil.getInstance().setString(sysAppIdKey, appId, this.redisAppIdTimelong);
										if (menuArr.size() <= 1) {
											List<TCommonPublicMenu> list = this.findPublicMenu(resId);
											if (list != null && list.size() > 0) {
												menuArr.addAll(list);
											}
										}
									}
									this.madeMenu(jsonMenuData.getString("data"), resId, logInfo, result, cfg);
									return result;
								}
							}
						}
					} catch (Exception e) {
						logInfo.setLevel(LogLevel.ERROR.toString());
						logInfo.setLogMessage(e.getMessage());
						log.error(JSONObject.fromObject(logInfo, cfg).toString(), e);
					}
				}
			}
		}
		result.setErrorMsg("获取用户菜单权限失败，请重试！");
		return result;
	}

	private List<TCommonPublicMenu> findPublicMenu(String resId) {
		return null;
//		return this.userInfoService.findAllBySQL(TCommonPublicMenu.class, "select * from t_common_public_menu m where m.select_res_id=?", null, false, resId);
	}

	/***
	 * @description 根据用户ID和资源ID获取用户拥有的菜单数据
	 * @author 冯亚
	 * @date 2019年10月21日 下午4:48:38
	 * @param userId
	 * @param resId
	 * @return ResultData
	 */
	@RequestMapping(value = "/findUserResourceByResIdToCache/{resId}/{userId}/{token}/{ip}", method = RequestMethod.GET)
	public ResultData findUserResourceByResIdToCache(@PathVariable("resId") String resId, @PathVariable("userId") String userId, @PathVariable("token") String token, @PathVariable("ip") String ip) {
		ResultData result = new ResultData();
		String key = userId + "-" + resId + "-" + token;
		JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		String redisMenuData = EhCacheUtil.getValue(key);
		if (!StringUtil.isNullOrEmpty(redisMenuData)) {
			result.setData(redisMenuData);
			return result;
		} else {
			redisMenuData = RedisClusterUtil.getInstance().getString(key);
			if (!StringUtil.isNullOrEmpty(redisMenuData)) {
				EhCacheUtil.put(key, redisMenuData);
				result.setData(redisMenuData);
				return result;
			}
		}
		String url = "/userResource/allChildResource/" + userId + "/" + resId;
		LogInfo logInfo = new LogInfo();
		String logId = UUID.randomUUID().toString();
		logInfo.setId(logId);
		logInfo.setSip(ip);
		logInfo.setDip(this.isoUrl);
		logInfo.setDip_service(url);
		logInfo.setLogType(LogType.receive.toString());
		logInfo.setTime(new Date());
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
		try {
			String menuData = IscSsoCall.appInfoApi(url);
			logInfo.setLevel(LogLevel.INFO.toString());
			logInfo.setLogMessage(menuData);
			log.info(JSONObject.fromObject(logInfo, cfg).toString());
			if (!StringUtils.isEmpty(menuData)) {
				JSONObject jsonMenuData = JSONObject.fromObject(menuData);
				if (jsonMenuData.get("resultCode") != null) {
					int resultCode = jsonMenuData.getInt("resultCode");
					if (resultCode == 200) {
						EhCacheUtil.put(key, jsonMenuData.getString("data"));
						RedisClusterUtil.getInstance().setString(key, jsonMenuData.getString("data"), 1200);
						result.setData(jsonMenuData.getString("data"));
						return result;
					}
				}
			}
		} catch (Exception e) {
			logInfo.setLevel(LogLevel.ERROR.toString());
			logInfo.setLogMessage(e.getMessage());
			log.error(JSONObject.fromObject(logInfo, cfg).toString(), e);
		}
		return result;
	}

	/**
	 * 对字符串菜单构造成菜单树
	 *
	 * @param menuStr 字符串菜单数据
	 * @param resId
	 * @param logInfo
	 * @param result
	 * @param cfg
	 */
	private void madeMenu(String menuStr, String resId, LogInfo logInfo, ResultData result, JsonConfig cfg) {
		JSONArray dataArr = JSONArray.fromObject(menuStr);
		log.info("dataArr:" + dataArr);
		if (dataArr != null && dataArr.size() > 0) {
			JSONObject jsonDataObj = this.getMenuData(dataArr, resId);
			if (logInfo != null) {
				logInfo.setLevel(LogLevel.INFO.toString());
				logInfo.setLogMessage("从统一权限平台获取数据:" + dataArr.toString());
			}
			log.info(JSONObject.fromObject(logInfo, cfg).toString());
			result.setData(jsonDataObj.toString());
		} else {
			if (logInfo != null) {
				logInfo.setLevel(LogLevel.WARN.toString());
				logInfo.setLogMessage("成功获取数据，数据为空！");
			}
			log.error(JSONObject.fromObject(logInfo, cfg).toString());
			result.setErrorMsg("成功获取数据，数据为空！");
			result.setData(dataArr.toString());
		}
	}

	/**
	 * @description 从cookie中根据名获取对应的值
	 * @author 冯亚
	 * @date 2019年8月7日 下午3:16:50
	 * @param tokenValue
	 * @param expiry
	 * @param response   void
	 */
	private String getValueFromCookie(String name, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if ((null != cookies) && (0 < cookies.length)) {
			for (Cookie cookie : cookies) {
				if ((null != cookie) && StringUtils.isNotBlank(cookie.getName()) && StringUtils.equals(cookie.getName().trim(), name) && StringUtils.isNotBlank(cookie.getValue())) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * @description 对数据进行结构调整，根据parentId进行构造树
	 * @author 冯亚
	 * @date 2019年10月28日 上午9:17:29
	 * @param dataArr
	 * @param resId
	 * @return JSONObject
	 */
	private JSONObject getMenuData(JSONArray dataArr, String resId) {
		JSONObject menuData = new JSONObject();
		List<MenuDto> list = new LinkedList<MenuDto>();
		Map<String, MenuDto> menuMap = this.makeMenuDto(dataArr, list);
		MenuDto rootDto = this.makeMenuData(menuMap, list);
//		this.makeMenuData(menuMap, list);
//		List<MenuDto> menuList = this.getMenuTree(menuMap);
		menuData.put("selectResId", resId);
		menuData.put("menuData", rootDto);
		log.info("menuData=" + JSONArray.fromObject(rootDto).toString());
		return menuData;
	}

	/**
	 * @description 根据菜单数据，对树进行构造
	 * @author 冯亚
	 * @date 2019年10月29日 下午3:43:02
	 * @param menuMap
	 * @param dataArr void
	 */
	private MenuDto makeMenuData(Map<String, MenuDto> menuMap, List<MenuDto> list) {
		MenuDto dto = null;
		MenuDto parentDto = null;
		MenuDto rootDto = null;
		for (int i = 0; i < list.size(); i++) {
			dto = list.get(i);
			if (!StringUtils.isEmpty(dto.getParentId())) {
				parentDto = menuMap.get(dto.getParentId());
				if (parentDto != null) {
					if (parentDto.getChildren() == null) {
						parentDto.setChildren(new ArrayList<MenuDto>());
					}
					parentDto.getChildren().add(dto);
				}
			} else if (StringUtil.isNullOrEmpty(dto.getPathId())) {
				rootDto = dto;
			} else {
				if (rootDto.getChildren() == null) {
					rootDto.setChildren(new ArrayList<MenuDto>());
				}
				rootDto.getChildren().add(dto);
			}
		}
		return rootDto;
	}

	/**
	 * @description 根据菜单json数据构造Map数据
	 * @author 冯亚
	 * @date 2019年10月28日 下午2:32:26
	 * @param dataArr
	 * @return Map<String,MenuDto>
	 */
	private Map<String, MenuDto> makeMenuDto(JSONArray dataArr, List<MenuDto> list) {
		JSONObject obj = null;
		MenuDto dto = null;
		for (int i = 0; i < dataArr.size(); i++) {
			obj = dataArr.getJSONObject(i);
			dto = new MenuDto();
			dto.setId(obj.getString("id"));
			dto.setName("null".equals(obj.getString("name")) ? null : obj.getString("name"));
			dto.setType("null".equals(obj.getString("typeId")) ? null : obj.getString("typeId"));
			dto.setUrl("null".equals(obj.getString("conent")) ? null : obj.getString("conent"));
			dto.setParentId("null".equals(obj.getString("parentId")) ? null : obj.getString("parentId"));
			dto.setSeqNumber("null".equals(obj.getString("seqNumber")) ? null : obj.getString("seqNumber"));
			dto.setPathId("null".equals(obj.getString("pathId")) ? null : obj.getString("pathId"));
			if (StringUtil.isNullOrEmpty(dto.getPathId())) {
				list.add(0, dto);
			} else {
				list.add(dto);
			}
		}
		Collections.sort(list);
		Map<String, MenuDto> menuMap = new HashMap<String, MenuDto>(dataArr.size());
		for (int i = 0; i < list.size(); i++) {
			dto = list.get(i);
			menuMap.put(dto.getId(), dto);
		}
		return menuMap;
	}
}
